#!/usr/bin/env python3
"""简单的stdio测试脚本"""

import subprocess
import json
import time
import sys

def test_basic_stdio():
    """测试基本的stdio通信"""
    print("开始基本stdio测试...")
    
    try:
        # 启动MCP服务器
        process = subprocess.Popen(
            [sys.executable, "main.py", "--mode", "stdio", "--config", "config"],
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            cwd="d:\\MCP\\mcp2"
        )
        
        print(f"MCP服务器已启动，进程ID: {process.pid}")
        
        # 等待服务器启动
        time.sleep(3)
        
        # 检查进程是否还在运行
        if process.poll() is not None:
            stdout, stderr = process.communicate()
            print(f"❌ 服务器启动失败")
            print(f"stdout: {stdout}")
            print(f"stderr: {stderr}")
            return False
        
        print("✅ 服务器启动成功")
        
        # 发送简单的初始化请求
        init_request = {
            "jsonrpc": "2.0",
            "id": 1,
            "method": "initialize",
            "params": {
                "protocolVersion": "2024-11-05",
                "capabilities": {},
                "clientInfo": {
                    "name": "test-client",
                    "version": "1.0.0"
                }
            }
        }
        
        request_json = json.dumps(init_request) + "\n"
        print(f"发送请求: {request_json.strip()}")
        
        # 发送请求
        process.stdin.write(request_json)
        process.stdin.flush()
        
        # 等待响应
        print("等待响应...")
        
        # Windows上使用简单的超时机制
        start_time = time.time()
        response = None
        
        while time.time() - start_time < 10:  # 10秒超时
            try:
                # 非阻塞读取
                import msvcrt
                if msvcrt.kbhit() or process.stdout.readable():
                    response = process.stdout.readline()
                    if response:
                        break
            except:
                pass
            time.sleep(0.1)
        
        if response:
            print(f"✅ 收到响应: {response.strip()}")
            try:
                response_data = json.loads(response)
                if "result" in response_data:
                    print("✅ 初始化成功")
                    return True
                else:
                    print(f"❌ 响应格式错误: {response_data}")
                    return False
            except json.JSONDecodeError as e:
                print(f"❌ 响应JSON解析失败: {e}")
                return False
        else:
            print("❌ 没有收到响应")
            return False
            
    except Exception as e:
        print(f"❌ 测试失败: {e}")
        return False
    finally:
        # 清理进程
        if 'process' in locals():
            try:
                process.terminate()
                process.wait(timeout=5)
            except:
                process.kill()

if __name__ == "__main__":
    success = test_basic_stdio()
    if success:
        print("\n🎉 stdio连接测试成功！")
        print("\n正确的MCP stdio连接配置:")
        print(json.dumps({
            "mcpServers": {
                "mcp2-stdio": {
                    "command": "python",
                    "args": ["main.py", "--mode", "stdio", "--config", "config"],
                    "cwd": "d:\\MCP\\mcp2",
                    "env": {
                        "PYTHONPATH": "d:\\MCP\\mcp2"
                    }
                }
            }
        }, indent=2))
    else:
        print("\n❌ stdio连接测试失败")
        sys.exit(1)